--- 单位合成物品
---@public
---@param whichUnit userdata 目标单位
---@param items nil|userdata|table<userdata> 空|物品|物品数组
hitem.synthesis = function(whichUnit, items)
    if (whichUnit == nil) then
        return
    end

    ---装备栏所有物品
    local uItem = {}

    hitem.forEach(
        whichUnit,
        function(enumItem, slotIndex)
            if enumItem ~= nil then
                local fg = true
                for index, value in ipairs(uItem) do
                    if value.itemName == hitem.getName(enumItem) then
                        fg = false
                        return
                    end
                end
                if fg then
                    table.insert(
                        uItem,
                        {
                            itemId = enumItem,
                            itemName = hitem.getName(enumItem),
                            itemNum = itemCount(whichUnit, enumItem)
                        }
                    )
                else
                    for i, value in ipairs(uItem) do
                        if value.itemName == hitem.getName(enumItem) then
                            uItem[i].itemNum = itemCount(whichUnit, enumItem)
                            return
                        end
                    end
                end
            end
        end
    )
    ---print_mbr(uItem)
    ---所有物品可制造物品
    local isOkItem = {}

    for i, v in ipairs(uItem) do
        local its = hechengTable(v.itemId)
        if its ~= nil then
            table.insert(isOkItem, its)
        end
    end
    ---所有可制造物品名
    local isIteam = {}
    ---满足材料合成方式
    local IteamHe = {}
    ---检测材料数量是否足够
    ---[1]
    for i1, v1 in ipairs(isOkItem) do
        ---[1]
        for i2, v2 in ipairs(v1) do
            ---[成长剑]
            for k3, v3 in pairs(v2) do
                local fg = false
                ---[1] 第一
                for i4, v4 in ipairs(v3) do
                    if v4.qty <= itemCountName(whichUnit, v4.keyName) then
                        fg = true
                    else
                        fg = false
                        break
                    end
                end
                if fg then
                    IteamHe[k3] = v3
                else
                    break
                end
            end
        end
    end
    ---删除装备
    for key, value in pairs(IteamHe) do
        for i2, v2 in ipairs(value) do
            itemDel(whichUnit, v2.keyName, v2.qty)
            ---print_mbr(v2.keyName)
        end
        ---合成装备
        local itemid =
            hitem.create(
            {
                id = hslk.n2i(key),
                x = 100,
                y = 400
            }
        )
        diyitem:add(itemid)
        hitem.pick(itemid, whichUnit)
        print_mbr("合成成功")
        hitem.synthesis(whichUnit, items)
        return
    end

    ---print_mbr(isOkItem)
    ---print_mbr(isOkItem)
end

---删除指定物品指定数量
function itemDel(u, Name, number)
    hitem.forEach(
        u,
        function(enumItem, slotIndex)
            if enumItem ~= nil then
                if hitem.getName(enumItem) == Name then
                    local c = cj.GetItemCharges(enumItem)
                    if c == 0 then
                        c = 1
                    end

                    if c > number then
                        c = c - number
                        number = 0
                        diyitem:SetItemCharges(enumItem, c)
                    else
                        number = number - c
                        hitem.del(enumItem, 0)
                        diyitem:del(enumItem)
                    end
                    if number == 0 then
                        return
                    end
                end
            end
        end
    )
end

---检测背包物品数量
function itemCount(u, key)
    local count = 0

    hitem.forEach(
        u,
        function(enumItem, slotIndex)
            if enumItem ~= nil then
                if hitem.getName(enumItem) == hitem.getName(key) then
                    local c = cj.GetItemCharges(enumItem)
                    if c == 0 then
                        c = 1
                    end
                    count = count + c
                end
            end
        end
    )
    return count
end
---检测背包物品数量
function itemCountName(u, name)
    local count = 0

    hitem.forEach(
        u,
        function(enumItem, slotIndex)
            if enumItem ~= nil then
                if hitem.getName(enumItem) == name then
                    local c = cj.GetItemCharges(enumItem)
                    if c == 0 then
                        c = 1
                    end
                    count = count + c
                end
            end
        end
    )
    return count
end

---合成Table信息
function hechengTable(enumItem)
    local hecheng = ""
    local profit = hitem.getId(enumItem)
    local tableData = {}
    --print_mbr(HSLK_SYNTHESIS.fragment[profit])
    local biao = {}
    if HSLK_SYNTHESIS.fragment[profit] ~= nil then
        for _key, _value in pairs(HSLK_SYNTHESIS.fragment[profit]) do
            for __key, __value in pairs(_value) do
                biao[__value.profit] = true
            end
        end
    end

    for _key, _value in pairs(biao) do
        if HSLK_SYNTHESIS.profit[_key] ~= nil then
            for index, value in ipairs(HSLK_SYNTHESIS.profit[_key]) do
                ---qty数量
                --print_mbr(value.qty)
                local bol = false

                local co = {}
                ---需求品
                local hechengXu = {}
                for i, v in ipairs(value.fragment) do
                    if profit == v[1] then
                        bol = true
                    end
                    ---需求品名字
                    local xItemkey = hitem.getName(v[1])
                    ---需求品数量
                    local xItemCount = v[2]
                    table.insert(
                        hechengXu,
                        {
                            ---需求品名字
                            keyName = hitem.getName(v[1]),
                            ---需求数量
                            qty = v[2]
                        }
                    )
                    table.insert(co, hitem.getName(v[1]) .. "×" .. v[2])
                end
                -- print_mbr(hechengXu)
                ---成品
                if bol then
                    ---成品名字
                    local ItemName = hitem.getName(_key)
                    ---成品数量
                    local itemCount = value.qty
                    hecheng = hecheng .. "|n" .. hitem.getName(_key) .. "×" .. value.qty .. "="
                    hecheng = hecheng .. table.concat(co, "+")

                    table.insert(tableData, {[ItemName] = hechengXu})
                end
            end
        end
    end
    if next(tableData) == nil then
        tableData = nil
    end
    return tableData
end
--- 获取物品的件数（以物品右下标的使用次数作为“件”）
--- 框架会自动强制最低件数为1
---@param it userdata
---@return number
hitem.getCharges = function(it)
    if (it == nil) then
        return 0
    end
    local c = cj.GetItemCharges(it)
    if c == 0 then
        c = 1
    end
    return c
end
--- 设置物品的使用次数
---@param it userdata
---@param charges number
hitem.setCharges = function(it, charges)
    if (it ~= nil and charges >= 0) then
        local itemTable = deep_copy(hslk.n2v(hitem.getName(it)))
        if itemTable.class ~= CONST_ITEM_CLASS.Permanent then
            -- print_mbr("设置")
            print_mbr(charges)
            cj.SetItemCharges(it, charges)
        end
    end
end
--[[
    创建物品
    options = {
        id = "I001", --物品ID
        charges = 1, --物品可使用次数（可选，默认为1）
        whichUnit = nil, --哪个单位（可选）
        x = nil, --哪个坐标X（可选）
        y = nil, --哪个坐标Y（可选）
        during = -1, --持续时间（可选，小于0无限制，如果有whichUnit，此项无效）
    }
]]
---@param options pilotItemCreate
---@return userdata|nil
hitem.create = function(options)
    if (options.id == nil) then
        print_err("hitem create -it-id")
        return
    end
    if (options.charges == nil) then
        options.charges = 1
    end
    if (options.charges < 1) then
        return
    end
    local charges = options.charges
    local during = options.during or -1
    -- 优先级 坐标 > 单位
    local x, y
    local id = options.id
    if (options.x ~= nil and options.y ~= nil) then
        x = options.x
        y = options.y
    elseif (options.whichUnit ~= nil) then
        x = hunit.x(options.whichUnit)
        y = hunit.y(options.whichUnit)
    else
        print_err("hitem create -position")
        return
    end
    if (type(id) == "string") then
        id = string.char2id(id)
    end
    local it
    local itemTable = {}
    -- 如果不是创建给单位，又或者单位已经不存在了，直接返回
    if (options.whichUnit == nil or his.deleted(options.whichUnit) or his.dead(options.whichUnit)) then
        -- 如果是shadow物品的明面物品，转成暗面物品再创建
        if (hitem.isShadowFront(id)) then
            id = string.char2id(hitem.shadowID(id))
        end
        -- 掉在地上
        it = cj.CreateItem(id, x, y)
        itemTable = deep_copy(hslk.n2v(hitem.getName(it)))
        if itemTable.class ~= CONST_ITEM_CLASS.Permanent then
            -- print_mbr("设置")
            cj.SetItemCharges(it, charges)
        else
            --print_mbr("设置0")
            cj.SetItemCharges(it, 0)
        end

        hitemPool.insert(CONST_CACHE.ITEM_POOL_PICK, it)
        if (options.whichUnit ~= nil and during > 0) then
            htime.setTimeout(
                during,
                function(t)
                    t.destroy()
                    hitem.del(it, 0)
                end
            )
        end
    else
        -- 单位流程
        it = cj.CreateItem(id, x, y)
        itemTable = deep_copy(hslk.n2v(hitem.getName(it)))
        if (hitem.getIsPowerUp(id)) then
            -- 如果是powerUp类型，直接给予单位，后续流程交予[hevent_default_actions.item.pickup]事件
            -- 因为shadow物品的暗面物品一定是powerup，所以无需额外处理
            if itemTable.class ~= CONST_ITEM_CLASS.Permanent then
                cj.SetItemCharges(it, charges)
            else
                cj.SetItemCharges(it, 0)
            end
            cj.UnitAddItem(options.whichUnit, it)
        elseif (hitem.getEmptySlot(options.whichUnit) > 0) then
            -- 没有满格,单位直接获得，后续流程交予[hevent_default_actions.item.pickup]事件
            if itemTable.class ~= CONST_ITEM_CLASS.Permanent then
                cj.SetItemCharges(it, charges)
            else
                cj.SetItemCharges(it, 0)
            end
            cj.UnitAddItem(options.whichUnit, it)
        elseif (hitem.isShadowFront(id)) then
            -- 满格了，如果是shadow的明面物品；转shadow再给与单位，后续流程交予[hevent_default_actions.item.pickup]事件
            id = string.char2id(hitem.shadowID(id))
            hitem.del(it)
            -- 掉在地上
            it = cj.CreateItem(id, x, y)
            if itemTable.class ~= CONST_ITEM_CLASS.Permanent then
                cj.SetItemCharges(it, charges)
            else
                cj.SetItemCharges(it, 0)
            end
            hitemPool.insert(CONST_CACHE.ITEM_POOL_PICK, it)
        else
            -- 满格了，如果是一般物品；掉在地上
            if itemTable.class ~= CONST_ITEM_CLASS.Permanent then
                cj.SetItemCharges(it, charges)
            else
                cj.SetItemCharges(it, 0)
            end
            hitemPool.insert(CONST_CACHE.ITEM_POOL_PICK, it)
        end
    end
    return it
end
hevent_default_actions.item.use =
    cj.Condition(
    function()
        local u = cj.GetTriggerUnit()
        if (his.silent(u)) then
            return
        end
        ---print_mbr("使用")
        local it = cj.GetManipulatedItem()
        local itId = hitem.getId(it)
        local perishable = hitem.getIsPerishable(itId)

        --检测是否使用后自动消失，如果不是，次数补回1
        if (perishable == false) then
            hitem.setCharges(it, cj.GetItemCharges(it) + 1)
        else
            hitem.subProperty(u, itId, 1)
            if (cj.GetItemCharges(it) <= 0) then
                hitem.del(it)
            end
        end

        --检测是否有匹配使用
        local triggerData = hcache.get(u, CONST_CACHE.ITEM_USED .. itId)
        if (triggerData ~= nil) then
            hitem.used(u, it, triggerData)
        end
        hcache.set(u, CONST_CACHE.ITEM_USED .. itId, nil)
    end
)